package com.xyz.rok.tools.service.impl;

import com.xyz.rok.tools.model.ApplyTitle;
import com.xyz.rok.tools.service.TitleQueueService;
import com.xyz.rok.tools.service.WxAppWrapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TitleQueueServiceImpl implements TitleQueueService {
    @Autowired
    private WxAppWrapperService wxAppWrapperService;
    private static ConcurrentHashMap<String, LinkedList<ApplyTitle>> queueMap = new ConcurrentHashMap(128);

    @Override
    public void addQueue(Integer title, Integer serverId, ApplyTitle applyTitle) {
        String key = serverId + "-" + title;
        if (queueMap.get(key) == null) {
            queueMap.put(key, new LinkedList<>());
        }
        queueMap.get(key).add(applyTitle);
    }

    @Override
    public ApplyTitle getQueueFirst(Integer title, Integer serverId) {
        String key = serverId + "-" + title;
        LinkedList<ApplyTitle> applyTitles = queueMap.get(key);
        if (applyTitles == null) {
            return null;
        }
        if (applyTitles.isEmpty()) {
            return null;
        }
        ApplyTitle applyTitle = applyTitles.getFirst();
        applyTitles.removeFirst();
        if(!applyTitles.isEmpty()){
            ApplyTitle next = applyTitles.getFirst();
            if (next != null) {
                wxAppWrapperService.pushQueueMsg(next.getUserId(), next.getTitle());
            }
        }
        return applyTitle;
    }
}
